package com.gitee.wsl.ext.collection


/**
 * This function permits an empty collection or a [single] object in the collection.
 *
 * @return null if empty or [single] object
 * @see single
 */
fun <T : Any> Iterable<T?>.emptyOrSingle(): T? {
    return when (this) {
        is List<T?> -> when (isEmpty()) {
            true -> null
            else -> single()
        }
        else -> iterator().emptyOrSingle()
    }
}

/**
 * See `Iterable`.[emptyOrSingle]
 */
fun <T : Any> Iterator<T?>.emptyOrSingle(): T? {
    return when (hasNext()) {
        true -> next().also {
            if (hasNext()) {
                // Copied from List.single
                throw IllegalArgumentException("List has more than one element.")
            }
        }
        else -> null
    }
}

/**
 * See `Iterable`.[emptyOrSingle]
 */
fun <T : Any> Sequence<T?>.emptyOrSingle(): T? {
    return iterator().emptyOrSingle()
}